﻿using KAKA.Domain;
using KAKA.Models;
using KAKA.Repository;
using Morus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcContrib;

namespace KAKA.Controllers
{
    public class TeamController : BaseController
    {
        public TeamController()
        {
            TeamRepository = IoC.Resolve<ITeamRepository>();
        }

        public ITeamRepository TeamRepository { get; private set; }

        [Administration]
        public ActionResult Index()
        {
            var teams = TeamRepository.GetAll()
                .ToList()
                .Select(r => new TeamModel()
                {
                    Id = r.Id.Shrink(),
                    Name = r.Name,
                    Intro = r.Introduction,
                    Sort = r.Sort.HasValue ? r.Sort.Value.ToString() : string.Empty
                })
                .OrderBy(r => r.Sort);

            return View(teams);
        }

        [Administration]
        public ActionResult Add()
        {
            return View();
        }

        [Administration]
        [ValidateAntiForgeryToken]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Add(TeamModel model)
        {
            if (ModelState.IsValid)
            {
                using (var uow = UnitOfWork.Begin())
                {
                    var team = new Team()
                    {
                        Id = Guid.NewGuid(),
                        Name = model.Name,
                        Introduction = model.Intro,
                        Sort = int.Parse(model.Sort)
                    };
                    TeamRepository.Add(team);

                    uow.Commit();
                }
            }

            return this.RedirectToAction(r => r.Index());
        }

        [Administration]
        public ActionResult Edit(string id)
        {
            var team = TeamRepository.Get(id.ToGuid());
            var model = new TeamModel()
            {
                Id = team.Id.Shrink(),
                Name = team.Name,
                Intro = team.Introduction,
                Sort = team.Sort.HasValue ? team.Sort.Value.ToString() : string.Empty
            };

            return View(model);
        }

        [Administration]
        [ValidateAntiForgeryToken]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(TeamModel model)
        {
            using (var uow = UnitOfWork.Begin())
            {
                var team = TeamRepository.Get(model.Id.ToGuid());

                team.Name = model.Name;
                team.Introduction = model.Intro;
                team.Sort = int.Parse(model.Sort);

                uow.Commit();
            }

            return this.RedirectToAction(r => r.Index());
        }
    }
}
